package com.wz.kwic;

import java.io.IOException;
//import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//import java.util.Locale;
public class Alphabetizer extends Filter{
    private ArrayList<String> al = new ArrayList<String>();

    Alphabetizer(Pipe input, Pipe output){
        super(input, output);
    }

    //对读入的数据进行排序
    protected void transform() throws IOException {
        String templine = null;

        //读入数据
        while((templine = input.readerLine()) != null){
            al.add(templine);
        }

        //按字母表排序
        Collections.sort(al, new AlphaabetizerComparator());

        //对排序后的数据进行输出
        for(int i = 0; i < al.size(); i++){
            output.writerLine(al.get(i));
        }
        input.closeReader();
        output.closeWriter();
    }
    //使用java提供的Collator类来实现比较
//    private class AlphaabetizerComparator implements Comparator<String> {
//
//    	private Collator collator;
//    	AlphaabetizerComparator(){
//    		this.collator = Collator.getInstance(Locale.ENGLISH);
//    	}
//
//		@Override
//		public int compare(String o1, String o2) {
//			return this.collator.compare(o1, o2);
//		}
//
//    }
    //自己写代码实现比较（使用字母的ascii值来进行比较)
    private class AlphaabetizerComparator implements Comparator<String> {

        @Override
        public int compare(String o1, String o2) {
            if (o1 == null || o2 == null) {
                throw new NullPointerException();
            }
            int compareValue = 0;
            char o1FirstCharacter = o1.charAt(0);
            char o2FirstCharacter = o2.charAt(0);
            if(this.isLetter(o1FirstCharacter) && this.isLetter(o2FirstCharacter)) {
                //如果是小写的字母的值，则转成对应的大写的字母的值
                o1FirstCharacter = this.toUpperCase(o1FirstCharacter);
                o2FirstCharacter = this.toUpperCase(o2FirstCharacter);
                compareValue = o1FirstCharacter - o2FirstCharacter;
            } else {
                throw new RuntimeException("必须是字母");
            }
            return compareValue;
        }

        private boolean isLetter(char c) {
            return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
        }

        private char toUpperCase(char c) {
            if (Character.isLowerCase(c)) {
                return Character.toUpperCase(c);
            }
            return c;
        }

    }
}
